<template>
  <n-drawer
    v-model:show="modelValue.toEdit"
    :width="600"
    :height="800"
    :placement="'bottom'"
  >
    <n-drawer-content
      :title="toADDFlag ? '添加' : '修改'"
      closable
      :mask-closable="false"
    >
      <n-form
        ref="formRef"
        :model="formValue"
        :rules="rules"
        :size="'medium'"
        label-placement="left"
        label-width="auto"
        require-mark-placement="right-hanging"
        :style="{ maxWidth: '640px' }"
      >
        <n-form-item
          label="名字"
          path="name"
        >
          <n-input
            v-model:value="formValue.name"
            placeholder="输入名字"
          />
        </n-form-item>
        <n-form-item
          label="描述"
          path="desc"
        >
          <n-input
            v-model:value="formValue.desc"
            type="textarea"
            placeholder="输入描述"
          />
        </n-form-item>
        <n-form-item
          label="在截止日期前多久提醒"
          path="beforeDDL2Mention"
        >
          <n-input-number v-model:value="formValue.timeMentionModal.beforeDDL2Mention" />
          <n-text type="error"
            >提醒时间:
            {{ timestampToDateTime(TimeMentionModal.computeMentionTime(formValue.timeMentionModal)) }}</n-text
          >
        </n-form-item>
        <n-form-item
          label="在截止日期前多久提醒的单位"
          path="beforeDDL2MentionUnit"
        >
          <n-select
            v-model:value="formValue.timeMentionModal.beforeDDL2MentionUnit"
            :options="TimeMentionModal.getMentionUnitMap()"
          />
        </n-form-item>
        <template v-if="modelValue.type === 1">
          <n-form-item
            label="截止日期"
            path="deadLine"
          >
            <n-date-picker
              v-model:value="formValue.timeMentionModal.deadLine"
              type="datetime"
              clearable
            />
          </n-form-item>
        </template>
        <template v-if="modelValue.type === 2">
          <n-form-item
            label="第一次打卡时间"
            path="beginMentionTime"
          >
            <n-date-picker
              v-model:value="formValue.timeMentionModal.beginMentionTime"
              type="datetime"
              clearable
            />
          </n-form-item>
          <n-form-item
            label="提醒周期标志"
            path="mentionFlag"
          >
            <n-select
              v-model:value="formValue.timeMentionModal.mentionFlag"
              :options="TimeMentionModal.getMentionFlagMap()"
            />
            <n-text type="error"
              >下次打卡时间:
              {{ timestampToDateTime(TimeMentionModal.computeNextClockTime(formValue.timeMentionModal)) }}</n-text
            >
          </n-form-item>
          <template v-if="formValue.timeMentionModal.mentionFlag === 1">
            <n-form-item
              label="提醒周期"
              path="mentionPeriod"
            >
              <n-input-number v-model:value="formValue.timeMentionModal.mentionPeriod" />
            </n-form-item>
          </template>
          <template v-if="formValue.timeMentionModal.mentionFlag === 2">
            <n-form-item
              label="提醒周期，用逗号分割，如1,2,3"
              path="mentionPeriod"
            >
              <n-input
                v-model:value="formValue.timeMentionModal.mentionPeriod"
                placeholder="输入提醒周期"
              />
            </n-form-item>
            <n-form-item
              label="自定义时，代表处在第几个"
              path="mentionPos"
            >
              <n-input-number v-model:value="formValue.timeMentionModal.mentionPos" />
            </n-form-item>
          </template>
          <n-form-item
            label="提醒周期单位"
            path="mentionUnit"
          >
            <n-select
              v-model:value="formValue.timeMentionModal.mentionUnit"
              :options="TimeMentionModal.getMentionUnitMap()"
            />
          </n-form-item>
        </template>
        <n-form-item
          label="状态"
          path="state"
        >
          <n-select
            v-model:value="formValue.state"
            :options="StateMoal.getStateMap4NewStage(toADDFlag)"
          />
        </n-form-item>
        <n-form-item>
          <n-button
            attr-type="button"
            @click="handleValidateClick"
          >
            {{ toADDFlag ? "添加" : "修改" }}
          </n-button>
        </n-form-item>
      </n-form>
    </n-drawer-content>
  </n-drawer>
</template>

<script
  lang="ts"
  setup
  generic="T extends object & { toEdit: boolean,toDelete:boolean,toDealRowId: number|undefined,type:number,state:string|undefined,stageId:number}"
>
import { StateMoal } from "@model/StateMoal";
import { TaskData, TimeMentionModal } from "@model/TaskList";
import { StageList, TaskIdsModal } from "@model/stage";
import { SurfaceSetting } from "@model/surfaceSetting";
import UseStage from "@pinias/UseStage";
import UseSurfaceSetting from "@pinias/UseSurfaceSetting";
import useTask from "@pinias/UseTask";
import pinia from "@pinias/pinia";
import { timestampToDateTime } from "@utils/DateUtils";
import { NForm, NFormItem, NInput, NDrawer, NDrawerContent, NButton, FormInst, useMessage } from "naive-ui";
import { ref, computed, watch } from "vue";

// 全局数据
const { getSurfaceSetting } = UseSurfaceSetting(pinia);
const surfaceSetting: SurfaceSetting = getSurfaceSetting();
const { getStageList } = UseStage(pinia);
const stageList: StageList = getStageList();
const { getTaskList } = useTask(pinia);
const taskList = getTaskList();

// 父组件数据
const props = defineProps<{ modelValue: T }>();
const emit = defineEmits(["update:modelValue"]);
const modelValue = computed({
  get: () => props.modelValue,
  set: val => emit("update:modelValue", val),
});
const getState = () => {
  return modelValue.value.state !== undefined && modelValue.value.state.length > 0
    ? modelValue.value.state
    : surfaceSetting.getTaskState(modelValue.value.type);
};
// 页面数据
const toADDFlag = computed(() => {
  return typeof modelValue.value.toDealRowId == "undefined";
});
const rules = {
  name: {
    required: true,
    message: "请输入名字",
    trigger: ["input"],
  },
  state: {
    required: true,
    message: "请选择状态",
    trigger: ["change"],
  },
};
const formRef = ref<FormInst | null>(null);
const getNewFormValue = () => {
  // console.log('getNewFormValue',toDealField);
  const time =
    modelValue.value.type === 1
      ? TimeMentionModal.setTaskBased(new TimeMentionModal(), null, 0, 1)
      : TimeMentionModal.setClockBased(new TimeMentionModal(), 0, 1, new Date().getTime(), 1, 1, 0, 1);
  const newOne = {
    id: surfaceSetting.maxId,
    name: "",
    desc: "",
    state: "stopping",
    timeMentionModal: time,
  };
  if (toADDFlag.value) {
    return newOne;
  } else {
    const oldData = taskList.getTaskDataById(modelValue.value.toDealRowId);
    if (oldData === undefined) {
      return newOne;
    } else {
      return {
        id: modelValue.value.toDealRowId,
        name: oldData?.name,
        desc: oldData?.desc,
        state: getState(),
        timeMentionModal: TimeMentionModal.copyTimeMentionModal(oldData.timeMentionModal),
      };
    }
  }
};
const formValue = ref(getNewFormValue());
// console.log('formValue',formValue.value);
watch(
  //也可以第一参数为响应式数据
  modelValue.value,
  () => {
    // console.log('formValue',formValue);
    formValue.value = getNewFormValue();
    // console.log('formValue2',formValue.value);
  },
);
const message = useMessage();
// 添加逻辑
const addNew = () => {
  const tosave = formValue.value;
  // console.log(
  //   "+++++++++++",
  //   formValue.value.timeMentionModal.deadLine,
  //   TimeMentionModal.computeMentionTime(formValue.value.timeMentionModal),
  //   formValue.value.timeMentionModal,
  // );
  if (
    formValue.value.timeMentionModal.deadLine !== null &&
    formValue.value.timeMentionModal.deadLine > 0 &&
    !(TimeMentionModal.computeMentionTime(formValue.value.timeMentionModal) > 0)
  ) {
    message.error("请选择提醒时间");
    return;
  }
  if (tosave !== undefined) {
    const showStage = modelValue.value.stageId; // surfaceSetting.getShowStage();
    const satgeData = stageList.getStageDataById(showStage);
    if (satgeData !== undefined) {
      const stateMoal = TaskIdsModal.getStateModal4Task(satgeData.task, modelValue.value.type);
      // console.log('toDealRow list',list)
      // console.log('formValue data',data)
      if (stateMoal !== undefined) {
        if (toADDFlag.value) {
          const list = StateMoal.getStateId(stateMoal, tosave.state);
          // console.log(list,tosave.id,stateMoal)
          if (tosave.id !== undefined) {
            list.push(tosave.id);
            taskList.addTaskData(
              new TaskData(
                tosave.id,
                tosave.name,
                modelValue.value.type,
                showStage,
                tosave.desc,
                tosave.timeMentionModal,
              ),
            );
            surfaceSetting.maxId++;
          }
        } else {
          const data = taskList.getTaskDataById(tosave.id);
          // console.log("addNew task", tosave, data);
          if (data !== undefined) {
            data.name = tosave.name;
            data.mentionTime = TimeMentionModal.computeMentionTime(tosave.timeMentionModal);
            data.desc = tosave.desc;
            data.timeMentionModal = tosave.timeMentionModal;
            data.type = modelValue.value.type;
            if (tosave.id !== undefined) {
              // console.log("addNew task", tosave.state, getState());
              const state = getState();
              if (tosave.state !== state) {
                StateMoal.changeIdState(stateMoal, tosave.id, state, tosave.state);
              }
            }
            // console.log('addNew task',stateMoal,tosave.id,surfaceSetting.getTaskState(modelValue.value.type),tosave.state);
          }
        }
      }
    } else message.error("阶段不存在或已删除");
  }
  surfaceSetting.TaskListKey = new Date().getTime();
  surfaceSetting.taskBoardList.key = new Date().getTime() + 10;
  modelValue.value.toEdit = false;
};
const handleValidateClick = (e: MouseEvent) => {
  // console.log('toDealRow',toDealRow);
  e.preventDefault();
  formRef.value?.validate(errors => {
    if (!errors) {
      // message.success("Valid");
      addNew();
    } else {
      console.log(errors);
      // message.error("Invalid");
    }
  });
};
</script>

<style scoped></style>
